lobsterlayui.main(['index', 'layer', 'form', 'element', 'table', 'laydate'], {
    data: {
        table: null,
        tableoptions: {},
        layerindex: 0,
        selectdata: {},
        orderTypelist: [],
    },
    pageload: function (right) {
        console.log(right);
        var sdate = this.getStartTime();
        var edate = this.getEndTime();
        if (sdate && edate) {
            $("#date").val(sdate + ' ~ ' + edate)
        }
        this.initevent();
        var self = this;
        this.initsele(function () {
            self.loaddata();
        });
    },
    //订单类型
    initsele: function (succ) {
        var self = this;
        lobsterlayui.GETAPI('tspay.getdic_ordertype').then(retdata => {
            var appedhtml = "";
            appedhtml += "<option value=\"-1\" selected>全部</option>";
            retdata.data.forEach(a => {
                appedhtml += "<option value=\"" + a.Code + "\">" + a.Name + "</option>";
            })
            $("[name='OrderType']").html(appedhtml);
            layui.form.render("select");

            self.data.orderTypelist = retdata.data;

            succ && succ();
        })
    },
    //初始化事件
    initevent: function () {
        var self = this;
        //查找reload,通过条件，查询网格的table重载数据显示到界面
        layui.form.on("submit(LAY-app-front-search)", function (data) {
            self.loaddata();
        });
        layui.laydate.render({
            elem: '#date'
            , type: 'date'
            , range: '~'
        });
        //监听行工具事件
        layui.table.on('tool(datatable)', function (obj) {  //tool是工具条事件名，table原始容器的属性
            var data = obj.data;//当前行数据
            var layEvent = obj.event;//获得lay-event的值
            if (obj.event === "refund") {
                self.openRefund(data);
            } else if (obj.event == "refunddetail") {
                window.selectdata = data;
                self.openRefundDetail(data);
            }

        });

    },
    //加载订单列表
    loaddata: function () {
        var self = this;
        var date = $("#date").val() || "";
        self.data.table = layui.table.render({
            elem: '#datatable',
            where: {
                orderNo: $("[name='orderNo']").val(),
                paystate: $("[name='paystate']").val(),
                orderType: $("[name='OrderType']").val(),
                sdate: date.split(' ~ ')[0],
                edate: date.split(' ~ ')[1],
            },
            headers: lobsterlayui.GetHeaderData(),
            url: lobsterlayui.GetLowCodeUrl("tspay.getpaylist"),
            height: 'full-130',
            cellMinWidth: 80,
            size: 'sm',
            page: true,
            parseData: function (res) {
                return {
                    code: res.code,
                    msg: res.msg,
                    count: res.data.count,
                    data: res.data.data
                }
            },
            cols: [[
                { width: "200", field: 'OrderNo', title: '订单号', fixed: 'left' },
                { width: "200", field: 'BusinessOrderNo', title: '业务订单号', fixed: 'left' },
                {
                    width: "200", field: 'OrderDate', title: '下单时间', templet: function (d) {
                        return (d.OrderDate || "").substring(0, 19);
                    }
                },
                // { width: "200", field: 'SubMchId', title: '商户号'},
                {
                    width: "120", title: '支付方式', templet: function (d) {
                        if (d.PayType == 1) {
                            return "微信支付";
                        } else if (d.PayType == 2) {
                            return "支付宝支付";
                        } else if (d.PayType == 3) {
                            return "零钱支付";
                        } else if (d.PayType == 4) {
                            return "组合支付";
                        }
                    }
                },
                { width: "120", field: 'TotalFee', title: '金额' },
                {
                    width: "180", title: '订单类型', templet: function (d) {
                        var filter = self.data.orderTypelist.filter(a => { return a.Code == d.OrderType });
                        if (filter != null && filter.length > 0) {
                            return filter[0].Name
                        }
                        return "";
                    }
                },
                {
                    width: "180", title: '订单状态', templet: function (d) {
                        if (d.PayState == 1) {
                            return "未支付";
                        } else if (d.PayState == 2) {
                            return "已支付";
                        } else if (d.PayState == 3) {
                            return "全额退费";
                        } else if (d.PayState == 4) {
                            return "部分退款" + "<span style='color:red;'>（" + d.RefundFee + "）</span>";
                        } else if (d.PayState == 5) {
                            return "已取消";
                        } else if (d.PayState == 6) {
                            return "退款中";
                        }
                    }
                },
                { width: "200", field: 'TradeNo', title: '交易流水号' },
                {
                    width: "200", field: 'PayDate', title: '支付成功时间', templet: function (d) {
                        return (d.PayDate || "").substring(0, 19);
                    }
                },
                { width: "200", field: 'TransactionId', title: '第三方支付流水号' },
                { field: 'operation', title: '操作', toolbar: '#edit', width: '200', fixed: 'right' }
            ]]
        })
    },
    //存为模板弹窗
    openRefund: function (data) {

        var self = this;
        self.data.selectdata = data;
        layer.open({
            type: 1
            , title: "退款申请"
            , content: $("#refund").html()
            , btn: ['保存', '取消']
            , maxmin: true
            , area: ['50%', '70%']  //宽，高
            , success: function (layero, index) {
                self.data.layerindex = index;
                self.binddata(data);

                //监听提交
                layui.form.on('submit(refundsubmit)', function (formdata) {
                    var field = formdata.field; //获取提交的字段 

                    if (!/^\d+(\.\d{1,2})?$/.test(field.RefundFee)) {
                        layer.msg("请输入正整数或两位以内小数");
                        return;
                    }
                    var refundFee = parseFloat(field.RefundFee);
                    if (refundFee == 0) {
                        layer.msg("退款金额不能未0");
                        return;
                    }

                    if (parseFloat(field.RefundFee) > parseFloat((data.TotalFee - data.RefundFee).toFixed(10))) {
                        layer.msg("退款金额不能大于总金额");
                        return;
                    }
                    if (!field.PassWord) {
                        layer.msg("请输入密码");
                        return;
                    }
                    if (!field.RefundDesc) {
                        layer.msg("请输入退款原因");
                        return;
                    }
                    var load = layer.msg('正在处理，请稍候', { icon: 16, time: 0, shade: [0.3, '#393D49'] });
                    self.refund(field, load);
                });
            }
            , yes: function (index, layero) {
                self.data.layerindex = index;
                $('#refundsubmit').trigger('click');
            }
        });
    },
    //申请退款
    refund: function (field, load) {
        var self = this;
        var RefundModel = {
            SubMchId: self.data.selectdata.SubMchId,
            OrderNo: self.data.selectdata.OrderNo,
            PayFee: self.data.selectdata.TotalFee,
            RefundRealFee: field.RefundFee,
            PassWord: field.PassWord,
            RefundDesc: field.RefundDesc,
            PayType: self.data.selectdata.PayType
        };
        lobsterlayui.POSTAPI('tspay.refundforself', RefundModel).then(retdata => {
            layer.msg('退款成功');
            self.data.table.reload();// 数据刷新
            layer.close(load);
            self.closelayer(); //关闭弹层 
        }).catch(res => {
            layer.close(load);
            layer.msg(res.msg);
        })
    },
    //绑定数据
    binddata: function (data) {
        $("#SubMchId").text(data.SubMchId);
        $("#BusinessOrderNo").text(data.BusinessOrderNo);
        $("#OrderNo").text(data.OrderNo);
        // $("#PayType").text(data.PayType);
        $("#TotalFee").text(data.TotalFee);
        $("#PayDate").text(data.PayDate.substring(0, 19));
        $("#RefundFee").text(data.RefundFee);
    },
    //关闭弹层
    closelayer: function () {
        layer.close(this.data.layerindex);
    },
    //退款详情
    openRefundDetail: function () {
        var self = this;
        layer.open({
            type: 2
            , title: "退款详情"
            , content: "refunddetail.html?appid="+lobsterlayui.GetAppId()
            , area: ['80%', '60%']
            // , btn: ['保存', '取消']
            , resize: false
            , success: function (layero, index) {

            }
            , btn2: function (index, layero) {

            }
            , cancel: function () {

            }
            , yes: function (index, layero) {

            }
        });
    },
    getEndTime: function () {
        var mdate = new Date();
        var year = mdate.getFullYear();
        var month = mdate.getMonth() + 1;
        if (month < 10)
            month = "0" + month;
        var ddate = mdate.getDate();
        if (ddate < 10)
            ddate = "0" + ddate;
        return year + "-" + month + "-" + ddate;
    },
    getStartTime: function () {
        var mdate = new Date();
        var year = mdate.getFullYear();
        var month = mdate.getMonth() + 1;
        if (month < 10)
            month = "0" + month;
        var ddate = mdate.getDate() - 3;
        if (ddate < 10)
            ddate = "0" + ddate;
        return year + "-" + month + "-" + ddate;
    }
})